<?php

namespace App\Http\Controllers\Web;

use App\Http\Model\Users;

use App\Http\Model\Services;
use Illuminate\Http\Request;
use App\Http\Requests\AddUserRequest;
use App\Http\Controllers\Web\BaseController;
use App\Http\Model\UserService;
use App\Http\Requests\AddUserServiceRequest;

class UsersController extends BaseController
{
    /**
     * 添加用户
     * @param AddUserRequest $request
     * @return void
     */
    public function addUser(AddUserRequest $request)
    {
        $service_info = Services::all(['id', 'service_name']);
        if ($request->isMethod('post')) {
            $user_id = intval($request->input('user_id', 0));

            $user_arr = Users::where('id', $user_id)->first();

            if (!isset($user_arr)) {
                $user_info = new Users();
            } else {
                $user_info = $user_arr;
            }
            $user_info->user_name = $request->input('user_name');
            $user_info->service_id = !empty($request->input('service_id')) ? $request->input('service_id') : 0;
            $user_info->save();

            return parent::success([], '操作成功');
        }
        return parent::success($service_info);
    }

    /**
     * 用户列表
     * @param Request $request
     * @return void
     */
    public function userList(Request $request)
    {
        $user_info = Users::orderBy('created_at', 'desc')->get();
        return parent::success($user_info);
    }

    /**
     * 添加用户服务接口
     * @param AddUserServiceRequest $request
     * @return void
     */
    public function addService(AddUserServiceRequest $request)
    {
        $user_service_id = intval($request->input('id'));
        $user_service_info = [];
        if ($user_service_id) {
            $user_service_info = UserService::where('id', $user_service_id)->first();
        }
        if ($request->isMethod('post')) {
            $user_service_id = intval($request->input('id'));
            $user_service_arr = UserService::where('id', $user_service_id)->first();
            if (!isset($user_service_arr->id)) {
                $user_service_info = new UserService();
            } else {
                $user_service_info = $user_service_arr;
            }

            $user_service_info->user_id = $request->input('user_id');
            $user_service_info->service_id = $request->input('serivce_id');
            $user_service_info->start_time = date('Y-m-d', strtotime($request->input('start_time')));
            $user_service_info->end_time = date('Y-m-d', strtotime($request->input('end_time')));
            $user_service_info->save();
            return parent::success([], '设置成功');
        }
        return parent::success($user_service_info);
    }
}
